package com.markbuikema.juliana32.adapter;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.Reminders;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.TextView;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import com.markbuikema.juliana32.R;
import com.markbuikema.juliana32.model.teams.Event;
import com.markbuikema.juliana32.model.teams.FacebookEvent;
import com.markbuikema.juliana32.model.teams.GameEvent;
import com.markbuikema.juliana32.util.DateTimeUtils;
import com.markbuikema.juliana32.util.Util;
import com.markbuikema.juliana32.util.facebook.FacebookManager;

public class AgendaEventAdapter extends BaseAdapter {

	private static final int VIEW_TYPE_FACEBOOK_EVENT = 0;
	private static final int VIEW_TYPE_GAME_EVENT = 1;
	private static final int VIEW_TYPE_HEADER = 2;
	private static final int VIEW_TYPE_COUNT = 3;

	private Context context;
	private List<Event> events;
	private int columnCount;

	public AgendaEventAdapter(Context context) {
		this.context = context;
		columnCount = context.getResources().getInteger(R.integer.column_count);
	}

	public void setEvents(List<Event> events) {
		this.events = events;
		notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return events == null ? 0 : events.size();
	}

	@Override
	public Object getItem(int position) {
		return events == null ? null : events.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public int getViewTypeCount() {
		return VIEW_TYPE_COUNT;
	}

	@Override
	public int getItemViewType(int position) {
		if (position < columnCount)
			return VIEW_TYPE_HEADER;
		else
			return getItem(position) instanceof FacebookEvent ? VIEW_TYPE_FACEBOOK_EVENT : VIEW_TYPE_GAME_EVENT;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (position < columnCount) {
			View view = new View(context);
			Resources res = context.getResources();

			final TypedArray styledAttributes = context.getTheme().obtainStyledAttributes(new int[] { android.R.attr.actionBarSize });
			int defaultMargin = (int) styledAttributes.getDimension(0, 0);
			styledAttributes.recycle();

			int statusBarHeight = Util.getStatusBarHeight(context);

			int gridSpacing = res.getDimensionPixelSize(R.dimen.card_margin);
			view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 2 * defaultMargin - gridSpacing + statusBarHeight));
			return view;
		}
		GameEventHolder geHolder;
		final Event event = (Event) getItem(position);

		switch (getItemViewType(position)) {
		case VIEW_TYPE_GAME_EVENT:

			final GameEvent game = (GameEvent) event;

			if (convertView == null) {
				convertView = LayoutInflater.from(context).inflate(R.layout.list_agenda_game, null);
				geHolder = new GameEventHolder();
				geHolder.homeLogo = (ImageView) convertView.findViewById(R.id.agenda_game_home_logo);
				geHolder.awayLogo = (ImageView) convertView.findViewById(R.id.agenda_game_away_logo);
				geHolder.homeTeam = (TextView) convertView.findViewById(R.id.agenda_game_home_team);
				geHolder.awayTeam = (TextView) convertView.findViewById(R.id.agenda_game_away_team);
				geHolder.homeGoals = (TextView) convertView.findViewById(R.id.agenda_game_home_goals);
				geHolder.awayGoals = (TextView) convertView.findViewById(R.id.agenda_game_away_goals);
				geHolder.referee = (TextView) convertView.findViewById(R.id.agenda_game_referee);
				geHolder.date = (TextView) convertView.findViewById(R.id.agenda_game_date);
				geHolder.location = (TextView) convertView.findViewById(R.id.agenda_game_location);
				geHolder.options = (ImageButton) convertView.findViewById(R.id.agenda_game_option_button);

				geHolder.homeGoals.setTypeface(Util.getRobotoSlabLight(context));
				geHolder.awayGoals.setTypeface(Util.getRobotoSlabLight(context));

				geHolder.referee.setTypeface(Util.getRobotoThin(context));
				geHolder.date.setTypeface(Util.getRobotoThin(context));
				geHolder.location.setTypeface(Util.getRobotoLight(context));

				convertView.setTag(geHolder);
			} else {
				geHolder = (GameEventHolder) convertView.getTag();
			}

			geHolder.homeTeam.setTypeface(Util.getRobotoCondensed(context), game.getThuisTeam().contains("Juliana") ? Typeface.BOLD
					: Typeface.NORMAL);
			geHolder.awayTeam.setTypeface(Util.getRobotoCondensed(context), game.getUitTeam().contains("Juliana") ? Typeface.BOLD
					: Typeface.NORMAL);

			final ImageButton options = geHolder.options;
			options.setOnClickListener(new OnClickListener() {

				@TargetApi(Build.VERSION_CODES.KITKAT)
				@Override
				public void onClick(View v) {
					final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
					PopupMenu menu = new PopupMenu(context, options);
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
						options.setOnTouchListener(menu.getDragToOpenListener());
					}

					Menu m = menu.getMenu();
					MenuInflater inflater = menu.getMenuInflater();

					inflater.inflate(R.menu.agenda_game, m);

					MenuItem notItem = m.findItem(R.id.action_notifications);

					Set<String> ids = prefs.getStringSet("game_notifications", null);
					if (ids != null) {
						notItem.setChecked(ids.contains(game.getId()));
					} else {
						notItem.setChecked(false);
					}

					menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {

						@Override
						public boolean onMenuItemClick(MenuItem item) {
							switch (item.getItemId()) {
							case R.id.action_navigate:
								String uri = "geo:0,0?q=" + game.getLocationAddress() + " " + game.getLocationZip() + " "
										+ game.getLocationCity();
								uri.replace(" ", "+");

								Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
								if (intent.resolveActivity(context.getPackageManager()) != null) {
									context.startActivity(intent);
								}
								break;
							case R.id.action_notifications:

								item.setChecked(!item.isChecked());

								Set<String> ids = prefs.getStringSet("game_notifications", null);

								if (ids == null)
									ids = new HashSet<String>();

								if (item.isChecked()) {
									ids.add(game.getId());
								} else {
									ids.remove(game.getId());
								}

								prefs.edit().putStringSet("game_notifications", ids).commit();

								break;
							case R.id.action_add_to_calendar:
								Intent calendarIntent = new Intent(Intent.ACTION_EDIT);
								calendarIntent.setType("vnd.android.cursor.item/event");

								String location = game.getLocationName() + " " + game.getLocationAddress() + " " + game.getLocationZip()
										+ " " + game.getLocationCity();
								String description;
								if (game.getCompType().equals("R"))
									description = "Competitiewedstrijd";
								else if (game.getCompType().equals("B"))
									description = "Bekerwedstrijd";
								else if (game.getCompType().equals("N"))
									description = "Nacompetitie";
								else
									description = "Oefenwedstrijd";

								calendarIntent.putExtra(Events.TITLE, game.getThuisTeam() + " - " + game.getUitTeam());
								calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, game.getDate());
								calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, game.getDate() + DateTimeUtils.GAME_IN_MS);
								calendarIntent.putExtra(Events.EVENT_LOCATION, location);
								calendarIntent.putExtra(Events.ALL_DAY, false);
								calendarIntent.putExtra(Events.DESCRIPTION, description);
								calendarIntent.putExtra(CalendarContract.Reminders.CALENDAR_ID, 5854262);
								calendarIntent.putExtra(Reminders.HAS_ALARM, true);
								context.startActivity(calendarIntent);
								break;
							}
							return true;
						}
					});
					menu.show();
				}
			});

			UrlImageViewHelper.setUrlDrawable(geHolder.homeLogo, game.getThuisLogo());
			UrlImageViewHelper.setUrlDrawable(geHolder.awayLogo, game.getUitLogo());

			geHolder.homeTeam.setText(game.getThuisTeam());
			geHolder.awayTeam.setText(game.getUitTeam());

			if (game.getThuisGoals().equals("null")) {
				geHolder.homeGoals.setVisibility(View.GONE);
			} else {
				geHolder.homeGoals.setText(game.getThuisGoals());
				geHolder.homeGoals.setVisibility(View.VISIBLE);
			}

			if (game.getUitGoals().equals("null")) {
				geHolder.awayGoals.setVisibility(View.GONE);
			} else {
				geHolder.awayGoals.setText(game.getUitGoals());
				geHolder.awayGoals.setVisibility(View.VISIBLE);
			}

			if (game.getReferee().isEmpty())
				geHolder.referee.setVisibility(View.GONE);
			else {
				String ref = String.format(context.getResources().getString(R.string.referee), game.getReferee());
				geHolder.referee.setVisibility(View.VISIBLE);
				geHolder.referee.setText(ref);
			}

			geHolder.date.setText(game.getDateString());
			geHolder.location.setText(game.getLocationName() + ", " + game.getLocationCity());
			break;

		case VIEW_TYPE_FACEBOOK_EVENT:

			final FacebookEvent fbEvent = (FacebookEvent) event;

			FacebookEventHolder feHolder;
			if (convertView == null) {
				convertView = LayoutInflater.from(context).inflate(R.layout.list_agenda_fb, null);
				feHolder = new FacebookEventHolder();
				feHolder.date = (TextView) convertView.findViewById(R.id.agenda_event_date);
				feHolder.location = (TextView) convertView.findViewById(R.id.agenda_event_location);
				feHolder.options = (ImageButton) convertView.findViewById(R.id.agenda_event_option_button);
				feHolder.title = (TextView) convertView.findViewById(R.id.agenda_event_title);

				feHolder.date.setTypeface(Util.getRobotoThin(context));
				feHolder.location.setTypeface(Util.getRobotoLight(context));
				feHolder.title.setTypeface(Util.getRobotoLight(context));

				convertView.setTag(feHolder);
			} else {
				feHolder = (FacebookEventHolder) convertView.getTag();
			}

			feHolder.date.setText(fbEvent.getDateString());
			feHolder.title.setText(fbEvent.getTitle());
			feHolder.location.setText(fbEvent.getLocation());

			final ImageButton feOptions = feHolder.options;

			feOptions.setOnClickListener(new OnClickListener() {

				@TargetApi(Build.VERSION_CODES.KITKAT)
				@Override
				public void onClick(View v) {
					PopupMenu menu = new PopupMenu(context, feOptions);
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
						feOptions.setOnTouchListener(menu.getDragToOpenListener());
					}
					menu.inflate(R.menu.agenda_fb);
					menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {

						@Override
						public boolean onMenuItemClick(MenuItem item) {
							switch (item.getItemId()) {
							case R.id.action_open_facebook_event:

								String facebookScheme = "fb://event/" + fbEvent.getId();
								Intent facebookIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(facebookScheme));
								context.startActivity(facebookIntent);
								// TODO make it work when facebook app is not
								// installed
								break;
							case R.id.action_add_to_calendar:
								Intent calendarIntent = new Intent(Intent.ACTION_EDIT);
								calendarIntent.setType("vnd.android.cursor.item/event");

								String location = fbEvent.getLocation();

								calendarIntent.putExtra(Events.TITLE, fbEvent.getTitle());
								calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, fbEvent.getDate());
								calendarIntent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, fbEvent.getEndTime());
								calendarIntent.putExtra(Events.EVENT_LOCATION, location);
								calendarIntent.putExtra(Events.ALL_DAY, false);
								calendarIntent.putExtra(CalendarContract.Reminders.CALENDAR_ID, 5854262);
								calendarIntent.putExtra(Reminders.HAS_ALARM, true);
								context.startActivity(calendarIntent);
								break;
							}
							return true;
						}
					});
					menu.show();
				}
			});

			break;
		}

		return convertView;

	}

	private class GameEventHolder {
		ImageView homeLogo;
		ImageView awayLogo;
		TextView homeTeam;
		TextView awayTeam;
		TextView homeGoals;
		TextView awayGoals;
		TextView date;
		TextView location;
		TextView referee;
		ImageButton options;
	}

	private class FacebookEventHolder {
		TextView date;
		TextView location;
		TextView title;
		ImageButton options;
	}

}
